<template>
	<view class="content">
		<!-- 订单信息展示 -->
		<view class="message-box" v-if="viewData">
			<p class="p">订单编号：{{ viewData.work_number }}</p>
			<p class="p">当前状态：{{ viewData.state }}</p>
			<p class="p">订单类型：{{ viewData.the_type_of_order }}</p>
			<p class="p">维修产品：{{ viewData.repair_the_product }}</p>
			<p class="p">负责人：{{ viewData.head }}</p>
			<p class="p">现场联系人：{{ viewData.on_site_contacts }}</p>
			<p class="p">队员：{{viewData.duiyuan}}</p>
			<view class="p">
				报修故障：{{viewData.break_desc}}
			</view>
			<view class="p">
				修复说明：{{viewData.fix_desc}}
			</view>
			<view class="btn-box-top">
				<view class="btn" >
					领用/退回
				</view>
				<view class="btn" @click="gotoLingyongXiangqing()">
					查看备件
				</view>
			</view>
			<view class="btn-box-box">
				<view class="btn"  @click="_baoxiaoShengcheng()">创建报销单</view>
				<view class="btn" @click="gotoBaoxiaoList()">查看报销单</view>
			</view>
		</view>

		<!-- 报修故障输入 -->
		<view class="input-box" v-if="viewJson.paigong">
			<p>报修故障：</p>
			<textarea disabled class="input" v-model="viewData.break_desc" placeholder="请输入"></textarea>
		</view>

		<!-- 检测过程输入 -->
		<view class="input-box" v-if="viewJson.jiance">
			<p>检测过程：</p>
			<textarea class="input" v-model="viewJson.internal_notes" placeholder="请输入检测过程"></textarea>
		</view>

		<!-- 维修过程输入 -->
		<view class="input-box" v-if="viewJson.weixiu">
			<p>维修过程：</p>
			<textarea class="input" v-model="viewJson.repair_detail" placeholder="请输入维修过程"></textarea>
		</view>

		<!-- 维修说明输入 -->
		<!-- 		<view class="input-box" v-if="viewJson.weixiu || viewJson.internal_notes == ''">
			<p>维修说明：</p>
			<textarea disabled class="input" v-model="viewJson.internal_notes" placeholder="请输入维修说明"></textarea>
		</view> -->

		<!-- 领用说明 -->
		<view class="lingyong-box">
			<p></p>
		</view>

		<!-- 现场图片 -->
		<view class="img-box">
			<p v-if="imgList[0]">现场图片：</p>
			<view class="img-item" v-if="imgList[0]">
				<image class="img" v-for="(item,i) in imgList" :key="i" :src="base64(item.photo)" mode=""
					@click="checkSeeImg(i)"></image>
			</view>
			<view class="noimg" v-if="!imgList[0]">
				<p>
					没有图像,请上传相关图片
				</p>
			</view>
		</view>

		<!-- 操作按钮 -->
		<view class="btn-box" v-if="showData">
			<view class="btn" @click="_imgUpLoad()">图片上传</view>
			<view class="btn" @click="saveData()">保存修改</view>
			<view class="btn" @click="_saveJianyankaishi()" v-if="buttonShow == 0">检验开始</view>
			<view class="btn" @click="_saveJianyanWancheng()" v-if="buttonShow == 1">检验完成</view>
			<view class="btn" @click="_saveStartWeixiu()" v-if="buttonShow == 2">维修开始</view>
			<view class="btn" @click="doneButton()" v-if="buttonShow == 3">维修完成</view>
			<view class="btn" @click="huituiBox()" v-if="backShow && viewData.state != '检测'">状态回退</view>
		</view>
	</view>
</template>

<script setup>
	import {
		reactive,
		ref
	} from 'vue';
	import {
		getMaintainConfig,
		getMaintainPhotosList,
		saveMaintainData,
		saveDone,
		saveJianyanWancheng,
		saveJianyankaishi,
		saveStartWeixiu,
		stateBackBtn,
		baoxiaoShengcheng
	} from '@/api/maitain.js';
	import {
		onLoad
	} from '@dcloudio/uni-app';
	import {
		base64,
		getData
	} from '@/tools/tools.js'
	import {
		baseUrl
	} from '@/api/base_url.js'

	const viewJson = reactive({
		fix_desc: '',
		repair_detail: '',
		internal_notes: '',
		weixiu: false,
		jiance: false,
		wangong: false,
		paigong: false
	})
	const buttonShow = ref(0)
	const viewData = ref({});
	const imgList = ref([])
	const recid = ref('')
	const save = ref(false)
	const showData = ref(true)
	const backShow = ref(false)
	// 获取详情
	const _getMaintainConfig = (id) => {

		// 数据重置
		viewJson.fix_desc = ''
		viewJson.repair_detail = ''
		viewJson.internal_notes = ''
		viewJson.weixiu = false
		viewJson.jiance = false
		viewJson.wangong = false

		buttonShow.value = 0
		viewData.value = {}
		save.value = false

		getMaintainConfig(id).then((res) => {
			console.log('派单详情', res);
			viewData.value = res;

			if (res.state == '派工') {
				viewJson.paigong = true
			}

			if (res.state == '检测中') {
				viewJson.jiance = true
			}

			if (res.state == '维修中') {
				viewJson.weixiu = true
			}

			if (res.repair_detail != false) {
				viewJson.repair_detail = res.repair_detail
			}

			if (res.internal_notes != false) {
				viewJson.internal_notes = res.internal_notes
			}


			if (res.state == '检测') {
				buttonShow.value = 0
			}

			if (res.state == '检测中') {
				buttonShow.value = 1
				backShow.value = true
			}

			if (res.state == '维修') {
				buttonShow.value = 2
				backShow.value = true
			}

			if (res.state == '维修中') {
				buttonShow.value = 3
				backShow.value = true
			}

			if (res.state == '已完成') {
				showData.value == false
			}

			console.log(buttonShow.value);

		})
	};
	// 获取图标
	const _getMaintainPhotosList = (id) => {
		recid.value = id
		getMaintainPhotosList(id).then((res) => {
			console.log('图片列表', res);
			if (res.photo_list[0]) {
				imgList.value = res.photo_list;
			} else {

			}
		})
	}
	// 图片上传
	const _imgUpLoad = () => {

		uni.chooseImage({
			count: 9, // 最多允许选择9张图片
			success: async (chooseImageRes) => {
				const tempFilePaths = chooseImageRes.tempFilePaths;
				console.log('选择的临时文件路径:', tempFilePaths);

				// 获取公共参数
				const formData = {
					user_id: getData().id,
					password: getData().password,
					record_id: recid.value
				};

				try {
					// 创建上传任务数组
					const uploadTasks = tempFilePaths.map(filePath => {
						return new Promise((resolve, reject) => {
							uni.uploadFile({
								url: baseUrl + '/upload_photo',
								filePath: filePath,
								name: 'photo',
								formData: formData,
								success: resolve,
								fail: reject
							});
						});
					});

					// 等待所有上传完成
					await Promise.all(uploadTasks);

					// 所有上传完成后刷新列表
					setTimeout(() => {
						_getMaintainPhotosList(recid.value);
					}, 700);

					uni.showToast({
						title: '上传成功',
						icon: 'success'
					});
				} catch (error) {
					console.error('上传失败:', error);
					uni.showToast({
						title: '部分上传失败',
						icon: 'none'
					});
				}
			},
			fail: (err) => {
				console.error('选择图片失败:', err);
				uni.showToast({
					title: '选择图片失败',
					icon: 'none'
				});
			}
		});
	}

	// 显示图片
	const checkSeeImg = (index) => {

		// 生成完整图片地址数组
		const urls = imgList.value.map(item => base64(item.photo));
		uni.previewImage({
			current: index, // 指定当前显示图片索引
			urls: urls, // 所有图片地址数组
			loop: true, // 开启循环预览（可选）
			indicator: 'default' // 显示指示器（可选）
		});
	}



	// 保存修改
	const saveData = () => {
		let data = {
			id: recid.value,
			fix_desc: viewJson.fix_desc,
			internal_notes: viewJson.internal_notes,
			repair_detail: viewJson.repair_detail,
		}

		saveMaintainData(data).then((res) => {
			setTimeout(() => {
				_getMaintainConfig(recid.value)
				save.value = true
			}, 1000)
		})
	}

	//完成
	const doneButton = () => {
		if (!save.value) {
			uni.showModal({
				title: '提示',
				content: '请先保存！'
			})
			return
		}

		if (!imgList.value[0]) {
			uni.showModal({
				title: '提示',
				content: '请上传至少一张图片'
			})

			return
		}
		if (viewJson.repair_detail == "") {
			uni.showModal({
				title: '提示',
				content: '请输入维修过程'
			})
			return
		}

		saveDone(recid.value).then((res) => {
			console.log(res);

			setTimeout(() => {
				_getMaintainConfig(recid.value)
			}, 1000)
		})

	}

	// 维修开始
	const _saveStartWeixiu = () => {
		if (!save.value) {
			uni.showModal({
				title: '提示',
				content: '请先保存！'
			})
			return
		}
		saveStartWeixiu(recid.value).then((res) => {
			console.log(res);
			setTimeout(() => {
				_getMaintainConfig(recid.value)
			}, 1000)
		})
	}

	// 检验完成
	const _saveJianyanWancheng = () => {
		if (!save.value) {
			uni.showModal({
				title: '提示',
				content: '请先保存！'
			})
			return
		}
		saveJianyanWancheng(recid.value).then((res) => {
			console.log(res);
			setTimeout(() => {
				_getMaintainConfig(recid.value)
			}, 1000)
		})
	}

	// 检验开始
	const _saveJianyankaishi = () => {
		if (!save.value) {
			uni.showModal({
				title: '提示',
				content: '请先保存！'
			})
			return
		}
		saveJianyankaishi(recid.value).then((res) => {
			console.log(res);
			setTimeout(() => {
				_getMaintainConfig(recid.value)
			}, 1000)
		})
	}


	const gotoLingyongXiangqing = () => {
		uni.navigateTo({
			url: `/model/gongDan/gongDanLingyong?id=${recid.value}`
		})
	}

	const huituiBox = () => {
		let state = viewData.value.state
		let id = recid.value
		console.log(state);

		stateBackBtn(id, state).then((res) => {
			console.log(res);

			setTimeout(() => {
				_getMaintainConfig(recid.value)
			}, 1000)
		})
	}


	// 申请报销
	const _baoxiaoShengcheng = () => {
		baoxiaoShengcheng(recid.value).then((res) => {
			console.log(res);
			if (res.status == '已生成报销单') {
				uni.showToast({
					title: '已经生成报销单',
					icon: 'success'
				})
			}
		})
	}

	// 查看报销单列表
	const gotoBaoxiaoList = () => {
		uni.navigateTo({
			url:`/model/baoXiao/baoxiaoList?id=${recid.value}`
		})
	}

	onLoad((option) => {

		_getMaintainConfig(option.id);
		_getMaintainPhotosList(option.id)
	});
</script>

<style lang="scss" scoped>
	/* 样式保持不变 */
	.content {
		padding: 20rpx;

		.message-box {
			line-height: 40rpx;

			.top {
				display: flex;
				justify-content: space-between;
			}

			.btn-box-top {
				display: grid;
				grid-template-columns: repeat(2, 1fr);
				gap: 10rpx;
				padding: 10rpx;

				.btn {
					text-align: center;
					padding: 10rpx;
					border-radius: 10rpx;
					color: white;
					background-color: rgb(51.2, 126.4, 204);

				}
			}

			.btn-box-box {
				display: grid;
				grid-template-columns: repeat(2, 1fr);
				gap: 10rpx;
				padding: 10rpx;

				.btn {
					text-align: center;
					padding: 10rpx;
					border-radius: 10rpx;
					color: white;
					background-color: rgb(51.2, 126.4, 204);

				}
			}
		}

		.input-box {
			margin-top: 20rpx;

			.input {
				margin-top: 10rpx;
				width: calc(100% - 32rpx);
				padding: 10rpx;
				border: 1rpx solid gainsboro;
				height: 180rpx;
				border-radius: 10rpx;
			}
		}

		.img-box {
			margin-top: 20rpx;

			.img-item {
				display: grid;
				grid-template-columns: repeat(3, 1fr);
				/* 创建3列，每列宽度相等 */
				gap: 10rpx;

				/* 列与列之间的间距 */
				.img {
					width: calc(100%);
					height: 200rpx;
					padding: 1rpx;
					border: 1rpx solid gainsboro;
					margin-bottom: 1rpx;
				}
			}

			.noimg {
				text-align: center;
				padding: 40rpx;
				border: 1rpx solid gainsboro;
				border-radius: 10rpx;
			}
		}

		.btn-box {
			padding: 0 20rpx;
			margin-top: 20rpx;
			display: grid;
			grid-template-columns: repeat(2, 1fr);
			/* 创建4列，每列等宽 */
			gap: 10px;

			/* 列与列之间的间距 */
			.btn {
				padding: 20rpx 60rpx;
				color: white;
				background-color: rgb(51.2, 126.4, 204);
				border-radius: 10rpx;
				text-align: center;
			}
		}
	}
</style>